package com.example.filemonitor.monitor.service.impl;
import java.time.LocalDateTime;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.filemonitor.book.entity.Book;
import com.example.filemonitor.book.service.IBookService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.io.File;
import java.util.Date;

@Slf4j
@Service
public class FileListener extends FileAlterationListenerAdaptor {

    @Value("${monitor.rootPath}")
    String rootPath;

    @Resource
    private IBookService bookService;

    /**
     * 文件创建执行
     */
    public void onFileCreate(File file) {
        log.info("[新建文件]:{}" ,file.getAbsolutePath());
        Book book = new Book();

        book.setTitle(file.getName());
        book.setDescription(file.getName());
        book.setPath(file.getAbsolutePath().substring(file.getAbsolutePath().indexOf(rootPath)+rootPath.length()));
        book.setCreateTime(new Date());
        book.setUpdateTime(new Date());

        log.info("book:{}" ,book);

        bookService.save(book);
    }

    /**
     * 文件创建修改
     */
    public void onFileChange(File file) {
        log.info("[修改文件]:{}" , file.getAbsolutePath());

        Book book = bookService.getByPath(file.getAbsolutePath());
        book.setUpdateTime(new Date());

        bookService.save(book);


    }


    /**
     * 文件删除
     */
    public void onFileDelete(File file) {
        log.info("[删除文件]:{}" , file.getAbsolutePath());

        Book book = bookService.getByPath(file.getAbsolutePath());

        if(book != null){
            bookService.removeById(book);
        }

    }

    /**
     * 目录创建
     */
    public void onDirectoryCreate(File directory) {
        log.info("[新建目录]:{}" , directory.getAbsolutePath());
    }

    /**
     * 目录修改
     */
    public void onDirectoryChange(File directory) {
        log.info("[修改目录]:{}" , directory.getAbsolutePath());
    }

    /**
     * 目录删除
     */
    public void onDirectoryDelete(File directory) {
        log.info("[删除目录]:{}" , directory.getAbsolutePath());
    }

    public void onStart(FileAlterationObserver observer) {
        // TODO Auto-generated method stub
        super.onStart(observer);
    }

    public void onStop(FileAlterationObserver observer) {
        // TODO Auto-generated method stub
        super.onStop(observer);
    }

}
